package com.qfedu.spring.anno.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @auther asus
 * @date 2022/4/28 15:31
 * Spring配置类
 * 相当于替换之前的beams.xml(spring-config.xml)文件
 */
@Configuration  //标识当前类是一个配置类
@ComponentScan("com.qfedu.spring.anno")
public class SpringConfig {

    // 1、dataSource
    // @Bean: 定义一个bean,方法名dataSource就是bean的id,方法的返回值就是bean的class
    // <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" />
    @Bean
    public static DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db2202?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    // 2、sqlSessionFactory
    @Bean
    public static SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //注入数据源
        sqlSessionFactoryBean.setDataSource(dataSource());
        //获取mapper.xml资源文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
        //注入资源文件
        sqlSessionFactoryBean.setMapperLocations(resources);
        //配置实体类别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.qfedu.spring.anno.entity");
        return sqlSessionFactoryBean;
    }

    // 3、MapperScannerConfigurer
    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        //配置DAO层接口的包名
        configurer.setBasePackage("com.qfedu.spring.anno.dao");
        return configurer;
    }
}
